package com.youlu.campus.service.commission;

import com.youlu.campus.entity.commission.DistributorChannelActivityGmvStatistics;
import com.youlu.campus.entity.commission.DistributorChannelGmvStatistics;
import com.youlu.campus.entity.commission.dto.DistributorChannelGmvQueryDTO;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DistributorChannelGmvStatisticsService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MapperFacade mapperFacade;

    public List<DistributorChannelGmvStatistics> list(DistributorChannelGmvQueryDTO dto){
        String activityId = dto.getActivityId();
        Query query = new Query();
        if(StringUtils.isNotBlank(activityId)){
            query.addCriteria(Criteria.where("activityId").is(activityId));
        }
        Date startTime = dto.getStartTime();
        Date endTime = dto.getEndTime();
        if(Objects.nonNull(startTime)&&Objects.nonNull(endTime)){
            SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMdd");
            query.addCriteria(Criteria.where("dayDate").gte(Integer.valueOf(sdf.format(startTime))).lte(Integer.valueOf(sdf.format(endTime))));
        }
        query.with(Sort.by(Sort.Direction.ASC,"dayDate"));
        if(StringUtils.isBlank(activityId)){
            return this.mongoTemplate.find(query,DistributorChannelGmvStatistics.class);
        }

        List<DistributorChannelActivityGmvStatistics> list = this.mongoTemplate.find(query, DistributorChannelActivityGmvStatistics.class);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        List<DistributorChannelGmvStatistics> result = mapperFacade.mapAsList(list, DistributorChannelGmvStatistics.class);
        return result.stream().sorted(Comparator.comparing(DistributorChannelGmvStatistics::getDayDate)).collect(Collectors.toList());
    }

    /**
     * 统计渠道订单GMV
     * @param orderNo
     * @param activityId
     * @param channelId
     * @param orderAmount
     */
    @Async
    public void doGmv(String orderNo,String activityId,String channelId,Integer orderAmount){
        log.info("【渠道订单GMV】orderNo:{}|activityId:{},channelId:{},orderAmount:{}",orderNo,activityId,channelId,orderAmount);
        try {
            String nowDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String dateNow = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            Integer currentDate = Integer.valueOf(nowDate);
            String dayOfWeek = LocalDate.now().getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.CHINA);
            Query query = new Query();
            query.addCriteria(Criteria.where("dayDate").is(currentDate));
            boolean exists = this.mongoTemplate.exists(query, DistributorChannelGmvStatistics.class);
            Update update = new Update();
            update.inc("gmv",orderAmount);
            if(!exists){
                Date now = new Date();
                update.set("date",dateNow);
                update.set("dayOfWeek",dayOfWeek);
                update.setOnInsert("createdTime",now);
                FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
                findAndModifyOptions.upsert(Boolean.TRUE);
                findAndModifyOptions.returnNew(Boolean.TRUE);
                this.mongoTemplate.findAndModify(query,update,findAndModifyOptions,DistributorChannelGmvStatistics.class);
            }else{
                this.mongoTemplate.updateFirst(query,update,DistributorChannelGmvStatistics.class);
            }
            //活动GMV
            query = new Query();
            query.addCriteria(Criteria.where("activityId").is(activityId));
            query.addCriteria(Criteria.where("dayDate").is(currentDate));
            boolean existsChannelActivity = this.mongoTemplate.exists(query, DistributorChannelActivityGmvStatistics.class);
            if(!existsChannelActivity){
                Date now = new Date();
                update.set("date",dateNow);
                update.set("dayOfWeek",dayOfWeek);
                update.setOnInsert("createdTime",now);
                FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
                findAndModifyOptions.upsert(Boolean.TRUE);
                findAndModifyOptions.returnNew(Boolean.TRUE);
                this.mongoTemplate.findAndModify(query,update,findAndModifyOptions,DistributorChannelActivityGmvStatistics.class);
            }else{
                this.mongoTemplate.updateFirst(query,update,DistributorChannelActivityGmvStatistics.class);
            }
        }catch (Exception e){
          log.error("【渠道订单GMV】 orderNo:{}",orderNo,e);
        }

    }
}
